<template>
  <div class="p-1.5 box-border">
    <div class="flex justify-between">
      <div>
        <a-form
            layout="inline"
            :model="searchState"
            @finish="getAllRecipe"
          >
            <a-form-item label="产品名称">
              <a-input v-model:value="searchState.Name" placeholder="请输入产品名称" allowClear>
              </a-input>
            </a-form-item>
            <a-form-item label="产品型号">
              <a-input v-model:value="searchState.Code"  placeholder="请输入产品型号" allowClear>
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-button type="default" @click="ResetSearchState">重置</a-button>
              <a-button class="!ml-1.5" type="primary"  html-type="submit"> 查询  </a-button>
            </a-form-item>
          </a-form>
      </div>
      <div>
        <a-button type="default" @click="downLoadExcample">下载配方模板</a-button>
        <a-button type="default" class="!ml-1.5" @click="GoLoadRecipes">导入配方</a-button>
        <a-button type="default" class="!ml-1.5" @click="exportAllRecipe">导出全部</a-button>
        <a-button type="primary" class="!ml-1.5" @click="onGoAddRecipe">新增配方</a-button>
      </div>
    </div>
    <a-table :columns="columns" :data-source="roleList"  class="!mt-4" :bordered="true" :loading="loading"  :scroll="{ y: windowHeight - 180 }" :pagination="{current:searchState.Page,total:total,pageSize:searchState.PageSize,'show-size-changer':true}" @change="PageChange">

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'updatedAt'">
          <span>
            {{dayjs(record.updatedAt).format('YYYY-MM-DD HH:mm:ss')}}
          </span>
        </template>
        <template v-if="column.key === 'action'">
          <span>
            <a @click="GoEditRecipe(record)">查看或编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除此配方吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="confirmDell(record)"
            >
                      <a>删除</a>
            </a-popconfirm>
            <a-divider type="vertical" />
            <a @click="exportRecipe(record)">导出</a>
          </span>
        </template>
      </template>
    </a-table>
    <a-modal :width="960" v-model:open="openModal" :title="formValRef.id == 0 ? '新增配方':'编辑配方'" @ok="onModelOk">
      <a-form ref="formRef" :model="formValRef">
       <a-row :gutter="24">
        <a-col :span="12" v-for="(key,index) in Object.keys(EditFormOptions)" :key="index">
           <a-form-item :label="key" :name="key" :rules="[{ required: true, message: `请输入${key}!`, trigger: 'change' }]">
            <a-input :placeholder="`请输入${key}`" v-model:value="formValRef[key]" :type="index>1?'number':'text'">
              <template #suffix>
                {{EditFormOptions[key]}}
              </template>
            </a-input>
          </a-form-item>
        </a-col>
       </a-row>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup>
import { ref,onMounted,reactive,toRaw,onActivated } from 'vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { useRecipeBridge,useDotNetBridge, windowHeight } from '../tools/index';

const total = ref(0);
const searchState = reactive({
  Name: '',
  Code: '',
  Page:1,
  PageSize:10
});
const formRefInit = {
  id:0,
  产品名称: '',
  产品型号: "",
  脱脂设定压力上限值: "",
  脱脂设定压力下限值: "",
  粗洗喷淋泵过载上限值: "",
  粗洗液位下限值: "",
  陶化喷淋泵过载上限值: "",
  精洗喷淋泵过载上限值: "",
  水分炉温度上限值: "",
  水分炉温度下限值: "",
  固化炉温度上限值: "",
  固化炉温度下限值: "",
  精洗液位下限值: "",
  冷却室离心风机过载上限值: "",
  输送机设定速度: "",
  输送机设定频率: "",
}
const formValRef = reactive({...formRefInit});
const formRef = ref();


const columns = [
  {
    title: '产品型号',
    dataIndex: '产品型号',
    key: '产品型号',
    width: 200,
    align: 'center',
  },
  {
    title: '产品名称',
    dataIndex: '产品名称',
    key: '产品名称',
    align: 'center',
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
    key: 'updatedAt',
    width: 200,
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    width: 210,
    align: 'center',
  },
];
const roleList = ref([]);
const loading = ref(true);
const openModal = ref(false);
const recipeBridge = useRecipeBridge();
const dotNetBridge = useDotNetBridge();
//新增
const onGoAddRecipe = () => {
  openModal.value = true;
  for (const key in formRefInit) {
    if (Object.prototype.hasOwnProperty.call(formRefInit, key)) {
      formValRef[key] = formRefInit[key];
    }
  }
};

const confirmDell = async e => {
  console.log(e);
   const result = await recipeBridge.Del(JSON.stringify({id:e.id}));
    const res = JSON.parse(result);
      if(res.code==0){
        message.success("删除成功");
        getAllRecipe();
      }else{
        message.error(res.msg);
      }
};

//编辑
const GoEditRecipe = e => {
  openModal.value = true;
  for (const key in e) {
    if (Object.prototype.hasOwnProperty.call(e, key)) {
      formValRef[key] = e[key];
    }
  }
};

const onModelOk = () => {
  formRef.value
    .validate()
    .then(async () => {
      if(formValRef.id==0){
        const result = await recipeBridge.Add(JSON.stringify(formValRef));
        const res = JSON.parse(result);
          if(res.code==0){
            message.success("添加成功");
            openModal.value = false;
            getAllRecipe();
          }else{
            message.error(res.msg);
          }
        }else{
          const result = await recipeBridge.Update(JSON.stringify(formValRef));
          const res = JSON.parse(result);
            if(res.code==0){
              message.success("更新成功");
              openModal.value = false;
              getAllRecipe();
            }else{
              message.error(res.msg);
            }
        }
    })
    .catch(error => {
      console.log('error', error);
    });
};

const ResetSearchState = () => {
  searchState.Name = "";
  searchState.Code = "";
}
//获取所有配方
const getAllRecipe =async () => {
  loading.value = true;
  try {
    const result = await recipeBridge.GetAllList(JSON.stringify(searchState));
    const res = JSON.parse(result);
    loading.value = false;
    if(res.code==0){
      roleList.value = [...res.data.list];
      total.value = res.data.total;
    }else{
      message.error(res.msg);
    }
  } catch (error) {
     loading.value = false;
    console.log(error);
  }
};

const PageChange = (pagination) => {
  searchState.Page = pagination.current;
  searchState.PageSize = pagination.pageSize;
  getAllRecipe();
}



onMounted(() => {
  getAllRecipe();
})

onActivated(()=>{
  console.log("路由切换了");
})


const EditFormOptions = {
    产品名称: '',
    产品型号: "",
    脱脂设定压力上限值: "Mpa",
    脱脂设定压力下限值: "Mpa",
    粗洗喷淋泵过载上限值: "kw",
    粗洗液位下限值: "m³",
    陶化喷淋泵过载上限值: "kw",
    精洗喷淋泵过载上限值: "kw",
    精洗液位下限值: "m³",
    水分炉温度上限值: "℃",
    水分炉温度下限值: "℃",
    冷却室离心风机过载上限值: "kw",
    固化炉温度上限值: "℃",
    固化炉温度下限值: "℃",
    输送机设定速度: "m/s",
    输送机设定频率: "hz",
}
//下载模板
const downLoadExcample = () => {
  dotNetBridge.ExportExcel(JSON.stringify([{
    产品名称: '',
    产品型号: "",
    脱脂设定压力上限值: "Mpa",
    脱脂设定压力下限值: "Mpa",
    粗洗喷淋泵过载上限值: "kw",
    粗洗液位下限值: "m³",
    陶化喷淋泵过载上限值: "kw",
    精洗喷淋泵过载上限值: "kw",
    精洗液位下限值: "m³",
    水分炉温度上限值: "℃",
    水分炉温度下限值: "℃",
    冷却室离心风机过载上限值: "kw",
    固化炉温度上限值: "℃",
    固化炉温度下限值: "℃",
    输送机设定速度: "m/s",
    输送机设定频率: "hz",
    备注: "只填写数值，不用加单位，导入时此列删除！！！",
}]),"配方模板.xlsx");
}
//导出模版
const exportRecipe = (row) => {
  message.loading("正在导出，请稍等...");
   dotNetBridge.ExportExcel(JSON.stringify([{...row}]),"配方.xlsx").then(result=>{
    const res = JSON.parse(result);
    if(res.code==0){
      message.success("导出成功");
    }else{
      res.msg&&message.error(res.msg);
    }
  })
}
//导入配方
const GoLoadRecipes = () => {
message.loading("正在导入，请稍等...");
  recipeBridge.ImportExcelRecipe().then(result=>{
    const res = JSON.parse(result);
    if(res.code==0){
      message.success("导入成功");
      getAllRecipe();
    }else{
      res.msg&&message.error(res.msg);
    }
  })
}
//导出全部
const exportAllRecipe = async () => {
  try {
    const result = await recipeBridge.GetAllList(JSON.stringify({  Name: '',
      Code: '',
      Page:1,
      PageSize:1000}));
    const res = JSON.parse(result);
    loading.value = false;
    message.loading("正在导出，请稍等...");
    if(res.code==0){
      dotNetBridge.ExportExcel(JSON.stringify([...res.data.list]),"配方.xlsx").then(result2=>{
        const res2 = JSON.parse(result2);
        if(res2.code==0){
          message.success("导出成功");
        }else{
          res2.msg&&message.error(res2.msg);
        }
      })
    }else{
      message.error(res.msg);
    }
  } catch (error) {
     loading.value = false;
     console.log(error);
  }
   
}
</script>